package com.batch.job;

import com.batch.incrementer.MyTimeStampParamIncrementer;
import com.batch.pojo.User;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.Bean;


// 主要学习 Chunk 块(学习章节3.1)
// 学习当前Job，请将@SpringBootApplication 取消注释，并将其他Job的@SpringBootApplication 方法注释,否则会对当前结果产生干扰

/**
 * Chunk 包括三个部分（reader,processor,writer）
 * 执行顺序：dataA reader->dataA processor->dataB reader->dataB processor->dataA dataB writer
 *
 * chunsize 表示一趟读和写多少次
 * 如果使用泛型，需要在chunksize前加泛型
 *   .<User,User>chunk(3) // 【重要】 设置块size大小为3
 *
 */


//@SpringBootApplication
// EnableBatchProcessing 使spring创建springbatch操作相关类对象
@EnableBatchProcessing
public class ChunkJob1 {


    // Job构建工厂，用于构建Job对象
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    // Step构建工厂，用于构建 Step 对象
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    private int timer = 8;

    @Bean
    public ItemReader<User> reader01() {
        return () -> {
            if(timer --< 0) return null;
            System.out.println("reader...,timer:" + timer);
            return new User(001, "张三", 12);
        };
    }

    @Bean
    public ItemProcessor<User,User> processor01() {
        return (u) -> {
            System.out.println("processor " + u.getUserName() + "...");
            u.setUserName(u.getUserName() + (int) (100 * Math.random()));
            u.setUserAge(u.getUserAge() + 1);
            return u;
        };
    }

    @Bean
    public ItemWriter<User> writer01() {
        return (uList) -> {
            for (User u : uList) {
                System.out.println("writering " + u.toString() + "...");
            }
        };
    }


    // 构建Step
    @Bean
    public Step step1_01() {
        return stepBuilderFactory.get("step1_01")
                .<User,User>chunk(3) // 【重要】 设置块size大小为3
                .reader(reader01())
                .processor(processor01())
                .writer(writer01())
                .build();
    }



    // 构建Job
    @Bean
    public Job job1_01() {
        return jobBuilderFactory.get("chunk-job1_01").start(step1_01())
                .incrementer(new MyTimeStampParamIncrementer())
                .build();
    }


    public static void main(String[] args) {
        SpringApplication.run(ChunkJob1.class, args);
    }


}
